import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const initialState = {
    token:localStorage.getItem('token') || '',
};

const userStore = createSlice({
    name: 'auth',
    initialState,
    reducers:{
        setToken:(state,action) =>{
            state.token=action.payload
            localStorage.setItem('token',action.payload)
        }
    }
})

const {setToken} = userStore.actions

const userReducer = userStore.reducer

const fetchUser = (loginForm) => {
    return async (dispatch) => {
        try {
            const res = await axios.post("/api/api/auth/login",loginForm);
            dispatch(setToken(res.data.access_token))
        }catch (error) { 
            console.log(error.response.data.message)
            throw error
        }
            
       
        
    }
}

export {fetchUser, setToken}

export default userReducer